#include "sensor.h"
#include "adc_driver.h"
#include "avr_compiler.h"
int convert_result(float);
void init_adc(void)
{

	ADCA.CTRLA |= 0x1;	 // enable adc
	ADCA.CTRLB = ADC_RESOLUTION_12BIT_gc;	 // 12 bit conversion
	ADCA.REFCTRL = ADC_REFSEL_INT1V_gc | 0x02;	 // internal 1V bandgap reference
	ADCA.PRESCALER = ADC_PRESCALER_DIV8_gc;	 // peripheral clk/8 (2MHz/16=250kHz)
	ADCA.CH0.CTRL = ADC_CH_INPUTMODE_SINGLEENDED_gc;	 // single ended
	ADCA.CH0.MUXCTRL = A_SENSOR_1;	 // Start sensor = 0
}

void set_active_analog_sensor(int active_sensor_a){
		if(active_sensor_a == 4)
		{
			ADCA.CH0.MUXCTRL = A_SENSOR_0;
		}
		else if(active_sensor_a == 5)
		{
			ADCA.CH0.MUXCTRL = A_SENSOR_1;
		}
		else if(active_sensor_a == 6){
			ADCA.CH0.MUXCTRL = A_SENSOR_2;
		}
		else if(active_sensor_a == 7){
			ADCA.CH0.MUXCTRL = A_SENSOR_3;
		}
	}

int adc_read(){
	
	ADCA.CH0.CTRL |= ADC_CH_START_bm; // start conversion 

	while(!ADCA.CH0.INTFLAGS);
	int result = ADCA.CH0RES;
	result = convert_result(result);
	return result;
}
int convert_result(float result){
	float supply_voltage = 3.3;
	float resistance = 200;
	float voltage_reference = 1.0;
	float result_volt;
	float thermistor_resistance;
	int result_int;
	
	result_volt = (float)(result-(200))/4096;
	
	thermistor_resistance = ((resistance * supply_voltage) / result_volt) - resistance;
	
	//thermistor_resistance = resistance / ((supply_voltage/result_volt) -1 ); //Used for when thermistor is the one connected to the ground
	//result_int = (int) ((thermistor_resistance-100) * 100); //Calculation for creating value that can be multiplied with a constant to get the temperature in a pt100 thermistor with 2 decimals accuracy
	
	result_int = (int)thermistor_resistance;
	return result_int;
}